<template>
  <div>
    <a-modal :visible="visible" @before-open="open" :on-before-ok="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" width="800px" top="20%" :mask-closable="false">
      <template #title> {{ title }} </template>
      <div>
        <a-form auto-label-width ref="formRef" size="medium" :model="form">
          <a-space direction="vertical" :size="24">
            <a-row>
              <a-col :span="8">
                <a-form-item field="sort" label="排序">
                  <a-input-number hide-button :min="0" v-model="form.sort" placeholder="请输入" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="name" label="属性模板名称" :rules="rules.name">
                  <a-input v-model="form.name" placeholder="请输入" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" label="状态">
                  <a-switch v-model="form.status"></a-switch>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-item field="productCatgoryId" label="绑定类目" :rules="rules.productCatgoryId">
                  <a-cascader @change="" :max-tag-count="1" multiple check-strictly :options="categoryOptions" :field-names="{ value: 'id', label: 'name' }" v-model="form.productCatgoryId" placeholder="请选择" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="scenes" label="应用场景" :rules="rules.scenes">
                  <a-select mode="multiple" v-model="form.scenes" placeholder="请选择" allow-clear>
                    <a-option value="prodcut">产品资料</a-option>
                    <a-option value="purchase">采购参数</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-space>
        </a-form>
      </div>
      <div class="dyna-table">
        <div class="title">属性信息</div>

        <a-button type="primary" size="medium" @click="selProperty.visible = true">选择属性</a-button>

        <a-table class="table-singe-line" size="mini" :data="form.itemList" @change="handleChange" :pagination="false" :scroll="{ y: 300 }" :draggable="{ type: 'handle', width: 30 }" style="margin-top: 10px">
          <template #columns>
            <a-table-column v-for="item of columns" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
              <template v-if="item.title == '序号'" #cell="{ record, rowIndex }">
                {{ rowIndex + 1 }}
              </template>

              <template v-if="item.title == '属性编码'" #cell="{ record, rowIndex }">
                <span>{{ record.prop ? record.prop.code : record.code }}</span>
              </template>
              <template v-if="item.title == '属性中文名称'" #cell="{ record, rowIndex }">
                <span>{{ record.prop ? record.prop.name : record.propName }}</span>
              </template>
              <template v-if="item.title == '属性英文民称'" #cell="{ record, rowIndex }">
                <span>{{ record.prop ? record.prop.nameEn : record.propNameEn }}</span>
              </template>

              <template v-if="item.title == '必填'" #cell="{ record, rowIndex }">
                <a-switch v-model="record.propRequired"></a-switch>
              </template>
              <template v-else="item.title == '操作'" #cell="{ record, rowIndex }">
                <div style="width: 100%">
                  <!-- <template #drag-handle-icon>
                    <icon-drag-arrow class="icon" />
                  </template> -->
                  <!-- <icon-drag-arrow class="icon" /> -->
                  <icon-minus-circle class="icon" style="margin-left: 10px" @click="delPropItem(record, rowIndex)" />
                </div>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>

      <SelProperty ref="selProperty" @save="save" />
    </a-modal>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, computed, reactive } from 'vue'
  import { addPropsType } from '../type'
  import { Message, Modal } from '@arco-design/web-vue'
  import { getCategoryList, updatePropertyTemplate } from '@/api/product'
  import SelProperty from './selProperty.vue'
  import _ from 'lodash-es'

  const columns: any = [
    // {
    //   title: '序号',
    //   align: 'left',
    //   width: 40,
    // },
    {
      title: '属性编码',
      dataIndex: 'code',
      align: 'left',
      width: 150,
    },
    {
      title: '属性中文名称',
      dataIndex: 'propName',
      align: 'left',
      width: 150,
    },
    {
      title: '属性英文民称',
      dataIndex: 'propNameEn',
      align: 'left',
      width: 150,
    },
    {
      title: '必填',
      dataIndex: 'english',
      align: 'left',
      width: 60,
    },
    {
      title: '操作',
      align: 'left',
      width: 60,
    },
  ]

  export default defineComponent({
    name: 'addCateGory',
    emits: ['save'],
    props: ['detail'],
    components: { SelProperty },
    setup(props: addPropsType, { emit }) {
      let visible = ref(false)
      let categoryOptions: any = ref([])
      let form: any = ref({
        sort: '',
        // source: 'custom',
        name: '',
        productCatgoryId: [],
        itemList: [],
        status: true,
        scenes: '',
      })
      const formRef = ref()
      const selProperty = ref()
      const rules = {
        name: [{ required: true, message: '请输入属性中文名称' }],
        nameEn: [{ required: true, message: '请输入属性英文名称' }],
        productCatgoryId: [{ required: true, message: '请选择类目' }],
        scenes: [{ required: true, message: '请选择应用场景' }],
      }

      const handleOk = (done: any) => {
        console.log(form)

        formRef.value.validate(async (valid: any) => {
          if (!valid) {
            let params = _.cloneDeep(form.value)
            params.categoryList = []
            params.productCatgoryId.forEach((e: string) => {
              let obj = { productCatgoryId: e }
              params.categoryList.push(obj)
            })

            try {
              const res: any = await updatePropertyTemplate(params)
              if (res.code == 'SUCCESS') {
                form.value = {
                  sort: '',
                  // source: 'custom',
                  name: '',
                  productCatgoryId: [],
                  itemList: [],
                  status: true,
                }
                props.detail.type == 'add' ? Message.success('添加成功') : Message.success('编辑成功')
                visible.value = false
                emit('save')
              }
              done(true)
            } catch (error) {
              done(true)
            }
          } else {
            done(true)
          }
        })
      }
      const handleCancel = () => {
        formRef.value.resetFields()
        form.value = {
          sort: '',
          // source: 'custom',
          name: '',
          productCatgoryId: [],
          itemList: [],
          status: true,
        }
        visible.value = false
      }

      const title = computed(() => {
        if (props.detail.type == 'add') {
          return '新增属性'
        } else {
          return '编辑属性'
        }
      })

      const delPropItem = (item: any, index: any) => {
        if (item.id && props.detail.type == 'edit') {
          form.value.delItemIdList.push(item.id)
        }
        form.value.itemList.splice(index, 1)
      }

      const handleChange = (val: any) => {
        form.value.itemList = val
      }

      // 获取类目列表
      const getCategor = async () => {
        const res: any = await getCategoryList()
        categoryOptions.value = res.data
      }
      const open = () => {
        getCategor()

        if (props.detail.type == 'edit') {
          form.value = _.cloneDeep(props.detail.data)
          console.log(form.value)

          let arr = _.cloneDeep(form.value.categoryList)
          form.value.productCatgoryId = arr.map((e: any) => e.productCatgoryId)
          form.value.delItemIdList = []
        } else {
          form.value = {
            sort: '',
            // source: 'custom',
            name: '',
            productCatgoryId: [],
            itemList: [],
            status: true,
          }
        }
      }

      const save = (data: any) => {
        data.forEach((e: any) => {
          let index = form.value.itemList.findIndex((el: any) => {
            let name = el.prop ? el.prop.name : el.propName
            return e.propName == name
          })
          if (index == -1) {
            form.value.itemList.push(e)
          }
        })
      }

      return { visible, save, selProperty, open, handleOk, handleCancel, categoryOptions, delPropItem, title, form, rules, formRef, columns, handleChange }
    },
  })
</script>

<style lang="less" scoped>
  .icon {
    color: #2b65ef;
    font-size: 20px;
  }
  .dyna-table {
    // padding: 10px 20px;
    box-sizing: border-box;
    .title {
      font-size: 16px;
      height: 18px;
      line-height: 18px;
      margin-bottom: 20px;
      &::before {
        content: '';
        display: inline-block;
        width: 6px;
        height: 18px;
        background-color: #2561ef;
        float: left;
        margin-right: 5px;
        border-radius: 3px;
      }
      &::after {
        content: '';
        display: inline-block;
        width: calc(100% - 80px);
        margin: -9px 0 0 81px;
        border-top: 1px solid #f2f2f2;
        float: left;
      }
    }
  }
</style>
